<?php

namespace app\admin\controller;

use util\Tree;
use think\Db;
use app\admin\model\AuthRule as AuthRuleModel;

class AuthRule extends Backend
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $data = Db::name('auth_rule')->order(['sort' => 'asc', 'id' => 'asc'])->select();
            $data = $data ? Tree::dataToList($data) : [];
            $data = [
                'total' => count($data),
                'rows' => $data,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * 添加菜单权限
     *
     * @return void
     */
    public function add()
    {
        if ($this->request->isPost()) {
            //获取提交的数据
            $data = input('post.');
            //验证token

            //表单验证
            $this->validate_response($data, $this->modelName . '.add');

            Db::startTrans();
            //保存到数据库
            try {
                $res = AuthRuleModel::create($data);
                if ($res) {
                    //开始批量创建子菜单
                    $menus = AuthRuleModel::getChildrenInfos($res['id'], $res['name'], !empty($data['operates']) ? $data['operates'] : []);
                    if (!empty($menus)) {
                        $res2 = (new AuthRuleModel)->saveAll($menus);
                        if (!$res2) {
                            throw new \Exception('子菜单创建失败');
                        }
                    }
                }
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('添加失败：' . $e->getMessage());
            }

            if (!$res) {
                Db::rollback();
                $this->error('添加失败，请重试');
            }

            DB::commit();
            $this->success('添加完成');
        }

        $pid = input('param.pid/d', 0);
        $this->assign('pid', $pid);
        $rules = AuthRuleModel::getAvaliableRules();
        $this->assign('rules', $rules);
        return $this->fetch();
    }

    public function edit()
    {
        if ($this->request->isGet()) {
            $rules = AuthRuleModel::getAvaliableRules();
            $this->assign('rules', $rules);
        }
        return parent::edit();
    }
}
